package com.minisoft.ydac;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.minisoft.utils.LocationUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author JueSu
 * @description: TODO
 * @date 2025/3/17 10:01
 */
@Slf4j
public class ExportBuildingInfo {
    static Map<String, Map<String, Object>> saleOrgMap = new HashMap<>();

    static LocationUtils locationUtils = new LocationUtils();
    public static void main(String[] args) {
        initSaleOrgMap();
        ExcelReader reader = ExcelUtil.getReader("D:\\temp\\hb_page_info.xlsx");
        reader.setSheet(0);
        List<Map<String, Object>> list = reader.readAll();
        try (ExcelWriter writer = new ExcelWriter("D:\\temp\\buildinfo0317.xlsx")) {
//            baseInfo(list, writer);
            floorInfo(list, writer);
//            aroundInfo(list, writer);
        }

    }

    private static void aroundInfo(List<Map<String, Object>> list, ExcelWriter writer) {
        // 写入头部
        writer.setSheet(2);
        List<String> header = ListUtil.toList("大区", "城市", "项目ID", "项目推广名","医院","诊所","公园","影院","商超","菜市场","幼儿园","中小学","地铁站","公交站");
        writer.writeRow(header);

        for (Map<String, Object> page : list) {
            List<Object> record = createRecord(page);
            if (record == null) continue;
            JSONObject extinfo = JSONUtil.parseObj(page.get("extinfo"));
            record.add(extinfo.getStr("buildingName"));
            Double lat = extinfo.getDouble("lat");
            Double lng = extinfo.getDouble("lng");
            if(lat == null || lng == null) {
                log.error("lat or lng is null");
                continue;
            }
            record.add(getAroundInfo("医院",lat,lng));
            record.add(getAroundInfo("诊所",lat,lng));
            record.add(getAroundInfo("公园",lat,lng));
            record.add(getAroundInfo("影院",lat,lng));
            record.add(getAroundInfo("商超",lat,lng));
            record.add(getAroundInfo("菜市场",lat,lng));
            record.add(getAroundInfo("幼儿园",lat,lng));
            record.add(getAroundInfo("中小学",lat,lng));
            record.add(getAroundInfo("地铁站",lat,lng));
            record.add(getAroundInfo("公交站",lat,lng));
            writer.writeRow(record);
        }
    }

    //https://api.map.baidu.com/place/v2/search?query=%E6%95%99%E8%82%B2&scope=1&filter=&coord_type=2&page_size=10&page_num=0&output=json&ak=rO0F7z2joSZca2maZKrk1hsopaCw2HqW&sn=&timestamp=&radius=2000&ret_coordtype=gcj02ll&location=22.119747,113.364875
    private static String getAroundInfo(String key,double lat,double lng) {//lat,lng
        String location = lat + "," + lng;
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        String url = StrUtil.format("https://api.map.baidu.com/place/v2/search?query={}&scope=1&filter=&coord_type=2&page_size=10&page_num=0&output=json&ak=rO0F7z2joSZca2maZKrk1hsopaCw2HqW&sn=&timestamp=&radius=3000&ret_coordtype=gcj02ll&location={}", key, location);
        Request request = new Request.Builder()
                .url(url)
                .method("GET", null)
                .addHeader("Connection", "keep-alive")
                .addHeader("Pragma", "no-cache")
                .addHeader("Cache-Control", "no-cache")
                .addHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1 wechatdevtools/1.06.2306020 MicroMessenger/8.0.5 Language/zh_CN webview/")
                .addHeader("Accept", "*/*")
                .addHeader("Sec-Fetch-Site", "cross-site")
                .addHeader("Sec-Fetch-Mode", "cors")
                .addHeader("Sec-Fetch-Dest", "empty")
                .addHeader("Referer", "https://servicewechat.com/wx7f05ade0396f497c/devtools/page-frame.html")
                .addHeader("content-type", "application/json")
                .addHeader("Host", "api.map.baidu.com")
                .addHeader("Cookie", "BAIDUID=6FF4EE6839C989ECECD6CED183FFCAB4:FG=1")
                .build();
        try {
            Response response = client.newCall(request).execute();
            List<String> collect = JSONUtil.parseObj(response.body().string()).getJSONArray("results").stream().map(item -> {
                JSONObject itemObj = JSONUtil.parseObj(item);
                //name,location
                JSONObject locationObj = itemObj.getJSONObject("location");
                //计算距离，单位是公里
                double distance = locationUtils.calculateDistance(lat, lng, locationObj.getDouble("lat"), locationObj.getDouble("lng"));
                //如果小于1000米，单位是米,不保留小数，如果大于1000米，单位是公里，保留1位小数
                String distanceStr;
                if (distance < 1) {
                    distanceStr = String.format("%.0f米", distance * 1000); // 转换为米，不保留小数
                } else {
                    distanceStr = String.format("%.1f公里", distance); // 保留1位小数
                }

                return StrUtil.format("{}-{}", itemObj.getStr("name"), distanceStr);
            }).collect(Collectors.toList());
            return StrUtil.join("\n", collect);
        } catch (IOException e) {
            log.error("getAroundInfo请求失败", e);
        }
        return "";
    }
    private static void floorInfo(List<Map<String, Object>> list, ExcelWriter writer) {
        // 写入头部
        writer.setSheet(1);
        List<String> header = ListUtil.toList("大区", "城市", "项目ID", "项目推广名");
        //增加28个户型
        for (int i = 0; i < 28; i++) {
            header.addAll(ListUtil.toList("户型名称","户型描述","户型总价（万/套）","户型朝向","建筑面积（㎡）","套内面积（㎡）"));
        }
        writer.writeRow(header);

        for (Map<String, Object> page : list) {
            List<Object> record = createRecord(page);
            if (record == null) continue;
            JSONObject extinfo = JSONUtil.parseObj(page.get("extinfo"));
            record.add(extinfo.getStr("buildingName"));
            extinfo.getJSONArray("floorPlan").forEach(item -> {
                JSONObject floorPlan = JSONUtil.parseObj(item);
                record.add(floorPlan.getStr("name"));
                record.add(floorPlan.getStr("houseType"));
                record.add(floorPlan.getStr("housetype_price"));
                record.add(floorPlan.getStr("orientation"));
                record.add(floorPlan.getStr("houseArea"));
                record.add(floorPlan.getStr("houseArea2"));
            });
            writer.writeRow(record);
        }
    }

    private static void baseInfo(List<Map<String, Object>> list, ExcelWriter writer) {
        // 写入头部
        writer.setSheet(0);
        List<String> header = ListUtil.toList("大区", "城市", "项目ID", "项目推广名","开发商", "在售状态","产权年限","业态类型","物业费（元/月/㎡）","车位占比","容积率","绿化率","首开时间");
        writer.writeRow(header);

        for (Map<String, Object> page : list) {
            List<Object> record = createRecord(page);
            if (record == null) continue;
            JSONObject extinfo = JSONUtil.parseObj(page.get("extinfo"));
            record.add(extinfo.getStr("buildingName"));
//                headers.add(Arrays.asList("开发商", "在售状态","产权年限","业态类型","物业费（元/月/㎡）","车位占比","容积率","绿化率","首开时间"));
            record.add(extinfo.getStr("developer"));
            record.add(extinfo.getStr("houseStatus"));
            record.add(extinfo.getStr("propertyYears"));
            record.add(extinfo.getStr("buildingTypeText"));
            record.add(extinfo.getStr("propertyCosts"));
            record.add(extinfo.getStr("parkingRatio"));
            record.add(extinfo.getStr("volumeRatio"));
            record.add(extinfo.getStr("greenRatio"));
            record.add(extinfo.getStr("bookDate"));
            writer.writeRow(record);
        }
    }

    @Nullable
    private static List<Object> createRecord(Map<String, Object> page) {
        log.info("当前处理hfProjectId={}，sale_org_id={}", page.get("hfProjectId"), page.get("sale_org_id"));
        List<Object> record = new ArrayList<>();
        Map<String, Object> saleOrg = saleOrgMap.get(page.get("sale_org_id").toString());
        if (saleOrg == null) {
            System.out.println(page.get("sale_org_id"));
            return null;
        }
        try {
            JSONUtil.parseObj(page.get("extinfo"));
        } catch (Exception e) {
            log.info("extinfo异常，跳过");
            return null;
        }
        record.add(saleOrg.get("area_name"));
        record.add(saleOrg.get("city_name"));
        record.add(saleOrg.get("project_id"));
        return record;
    }

    private static void initSaleOrgMap() {
        ExcelReader reader = ExcelUtil.getReader("D:\\temp\\sale_team_sale_org_rel.xlsx");
        reader.setSheet(0);
        List<Map<String, Object>> list = reader.readAll();
        list.forEach(item -> {
            String saleOrgId = item.get("sale_org_id").toString();
            saleOrgMap.put(saleOrgId, item);
        });
    }
}
